package com.bjpower.controller;

import com.bjpower.models.dto.PayConfigDto;
import com.bjpower.models.dto.PaymentDto;
import com.bjpower.models.request.PayWayInfoRequest;
import com.bjpower.service.GetPayWayService;
import com.bjpower.service.PayMentService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Map;


@Controller
public class GetWayController {
    @Resource
    private GetPayWayService getPayWayService;

    @Resource
    private Map<String, PayMentService> paymentMap;

    private Logger logger = LoggerFactory.getLogger(GetWayController.class);



    @GetMapping("/pay/gateway")
    public String getPayWay(PayWayInfoRequest payWayInfoRequest, HttpServletRequest request, Model model){
        //根据商户名以及商品code查询数据库信息
        PayConfigDto configDto = getPayWayService.getPayWay(payWayInfoRequest, request);
        String view = "";
        //使用策略模式根据支付类型调用支付接口
        PayMentService payMentService = paymentMap.get(payWayInfoRequest.getWayCode());
        try{
            if (payMentService == null){
                throw new RuntimeException("支付类型错误");
            }
            PaymentDto paymentDto = payMentService.pay(payWayInfoRequest, configDto);
            //将信息存储到model
            model.addAttribute("configDto", configDto);
            //将商户信息返回给快钱页面
            view = paymentDto.getView();
            //返回支付信息到快钱页面
            return view;
        }catch (Exception e){
            model.addAttribute("msg",e.getMessage());
            view = "error";
            logger.error("{}-支付错误：{}" , payWayInfoRequest, e.getMessage());
            e.printStackTrace();
        }
        return view;

    }
}
